package sfeir.ergosum.filters;

import sfeir.ergosum.HiveActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {

    /**
     * The Action fired by the Android-System when a SMS was received. We are
     * using the Default Package-Visibility
     */
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    // @Override
    public void onReceive(Context context, Intent intent) {

        boolean hasCode = false;
        String code = "";
        String alias = "";

        if (intent.getAction().equals(ACTION)) {

            SharedPreferences mPrefs = context.getSharedPreferences(context
                    .getPackageName()
                    + "_preferences", Context.MODE_WORLD_READABLE);

            if (mPrefs.getBoolean("preference_filter_sms", false)) {
                Bundle bundle = intent.getExtras();

                if (bundle != null) {
                    Object[] pdusObj = (Object[]) bundle.get("pdus");
                    SmsMessage[] messages = new SmsMessage[pdusObj.length];
                    for (int i = 0; i < pdusObj.length; i++) {
                        messages[i] = SmsMessage
                                .createFromPdu((byte[]) pdusObj[i]);
                    }

                    // Feed the StringBuilder with all Messages found.
                    for (SmsMessage currentMessage : messages) {
                        // Actual Message-Content
                        String body = currentMessage.getDisplayMessageBody();

                        if (body.contains("#@ErgoSum#@")) {
                            hasCode = true;
                            int start = body.lastIndexOf("#@ErgoSum#@") + 12;
                            int stop = start + 23;
                            String usedArea = body.substring(start);
                            if (usedArea.length() > 22)
                                code = body.substring(start, stop);
                            if (usedArea.length() > 24)
                                alias = body.substring(stop + 1);
                        }
                    }
                }

                if (hasCode) {

                    // Start the Main-Activity
                    HiveActivity.startActivity(context, code, alias);
                }
            }
        }
    }
}